package fr.umlv.m2.jee.pmlv.web.professor;

import fr.umlv.m2.jee.pmlv.service.note.DisplayUserNote;
import fr.umlv.m2.jee.pmlv.service.note.DisplayUserThemeNote;
import fr.umlv.m2.jee.pmlv.service.note.IDisplayUserNoteService;
import fr.umlv.m2.jee.pmlv.service.note.IDisplayUserThemeNoteService;
import fr.umlv.m2.jee.pmlv.service.subject.DisplayAbstractTheme;
import fr.umlv.m2.jee.pmlv.service.subject.DisplaySubject;
import fr.umlv.m2.jee.pmlv.service.subject.IDisplayAbstractThemeService;
import fr.umlv.m2.jee.pmlv.service.subject.IDisplaySubjectService;
import fr.umlv.m2.jee.pmlv.service.user.User;
import fr.umlv.m2.jee.pmlv.service.user.impl.UserService;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import javax.naming.NamingException;
import javax.servlet.ServletContext;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

/**
 * Servlet wich represents page for a professor where he can mark students for a theme.
 * @author Stephanie
 */
public class MarkTheme extends HttpServlet {
    // Variables
    private static final int MAX_STUDENT_BY_PAGE = 15;
    private User user = null;   //Contains informations about user
    private List<Integer> years = new ArrayList<Integer>(); //Contains years when professor teaching a subject
    private long idTheme = -1;
    private DisplayAbstractTheme theme = null;
    private long idSubject = -1;
    private DisplaySubject subject = null;
    private List<User> students = new ArrayList<User>();
    private Map<String, DisplayUserNote> notes = new HashMap<String, DisplayUserNote>();    //Notes of students for subject selected
    private Map<String, DisplayUserThemeNote> themes_notes = new HashMap<String, DisplayUserThemeNote>();    //Notes of students for subject selected



    /**
     * @see HttpServlet#HttpServlet()
     */
    public MarkTheme() {
            super();
    }

    /**
    * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response).
    */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        doPost(request,response);
    }

    /**
    * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response).
    */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        //Data
        user = null;
        years.clear();
        idTheme = -1;
        theme = null;
        idSubject = -1;
        subject = null;
        students.clear();
        notes.clear();
        themes_notes.clear();


        //Retrieve informations about user
        HttpSession session = request.getSession(true);
        user = (User)session.getAttribute("user");
        years.addAll((List<Integer>)session.getAttribute("years"));

        //Retrieve informations about theme
        int tmp = 0;
        if(Calendar.getInstance(Locale.FRENCH).get(Calendar.MONTH)>9)
            tmp = Calendar.getInstance(Locale.FRENCH).get(Calendar.YEAR);
        else
            tmp = Calendar.getInstance(Locale.FRENCH).get(Calendar.YEAR) - 1;
        ServletContext context = getServletContext();
        WebApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(context);
        if(request.getParameter("theme")!=null)
        {
            IDisplayAbstractThemeService themeService = (IDisplayAbstractThemeService) applicationContext.getBean("defautDisplayAbstractThemeService");
            idTheme = Integer.parseInt(request.getParameter("theme"));
            theme = themeService.getAbstractThemeById(idTheme);
            UserService userService = (UserService) applicationContext.getBean("ldapUser");
            try {
                students.addAll(userService.getStudentBySubjectIdAndByYear(theme.getSubject().getId(), tmp));
            } catch (NamingException ex) { }
            IDisplayUserThemeNoteService noteThemeService = (IDisplayUserThemeNoteService) applicationContext.getBean("defautDisplayUserThemeNoteService");
            List<DisplayUserThemeNote> tmpNotes = noteThemeService.getDisplayUserThemeNoteByThemeAndByYear(idTheme,tmp);
            for(DisplayUserThemeNote note:tmpNotes)
            {
                themes_notes.put(note.getUid(), note);
            }
        }
        else if(request.getParameter("subject")!=null)
        {
            IDisplaySubjectService subjectService = (IDisplaySubjectService) applicationContext.getBean("defautDisplaySubjectService");
            idSubject = Integer.parseInt(request.getParameter("subject"));
            subject = subjectService.getDisplaySubjectbyId(idSubject);
            UserService userService = (UserService) applicationContext.getBean("ldapUser");
            try {
                students.addAll(userService.getStudentBySubjectIdAndByYear(idSubject, tmp));
            } catch (NamingException ex) { }
            IDisplayUserNoteService noteService = (IDisplayUserNoteService) applicationContext.getBean("defautDisplayUserNoteService");
            List<DisplayUserNote> tmpNotes = noteService.getNoteBySubjectAndByYear(idSubject,tmp);
            for(DisplayUserNote note:tmpNotes)
            {
                notes.put(note.getUid(), note);
            }
        }


        //Edit mark of students
        if(request.getParameter("ok")!=null && idSubject==-1)
        {
            HashMap<String, Float> new_notes= new HashMap<String, Float>();
            for(int i=0;i<students.size();i++)
            {
                if(request.getParameter("students"+i+"_mark").length()==0)
                    new_notes.put(students.get(i).getuId(),null);
                else
                    new_notes.put(students.get(i).getuId(), new Float( Float.parseFloat(request.getParameter("students"+i+"_mark")) ));
            }
            IDisplayUserThemeNoteService noteThemeService = (IDisplayUserThemeNoteService) applicationContext.getBean("defautDisplayUserThemeNoteService");
            noteThemeService.markTheme(idTheme, new_notes);
            IDisplayUserNoteService noteService = (IDisplayUserNoteService) applicationContext.getBean("defautDisplayUserNoteService");
            for(int i=0;i<students.size();i++)
            {
                noteService.recalculMarkBySubjectAndByYear(theme.getSubject().getId(), students.get(i).getuId(), tmp);
            }
            response.sendRedirect((String)session.getAttribute("back"));
        }
        else if(request.getParameter("ok")!=null)
        {
            HashMap<String, Float> new_notesexam= new HashMap<String, Float>();
            HashMap<String, Float> new_notes= new HashMap<String, Float>();
            for(int i=0;i<students.size();i++)
            {
                if(request.getParameter("students"+i+"_exam").length()==0) new_notesexam.put(students.get(i).getuId(),null);
                else new_notesexam.put(students.get(i).getuId(), new Float( Float.parseFloat(request.getParameter("students"+i+"_exam")) ));
                if(request.getParameter("students"+i+"_mark").length()==0) new_notes.put(students.get(i).getuId(),null);
                else new_notes.put(students.get(i).getuId(), new Float( Float.parseFloat(request.getParameter("students"+i+"_mark")) ));
            }
            IDisplayUserNoteService noteService = (IDisplayUserNoteService) applicationContext.getBean("defautDisplayUserNoteService");
            noteService.markBySubjectAndByYear(idSubject, new_notes, tmp);
            noteService.markExamBySubjectAndByYear(idSubject, new_notesexam, tmp);
            response.sendRedirect((String)session.getAttribute("back"));
        }
        else if(request.getParameter("cancel")!=null)
            response.sendRedirect((String)session.getAttribute("back"));

        //View
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();

        out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD XHTML 1.1//EN\" \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">");
        out.println("<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"fr\" >");

        out.println(" <head>");
        out.println("   <title>PMLV : Portail Universitaire de Marne-La-Vall&eacute;e</title>");
        out.println("   <meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\" />");
        out.println("   <link rel=\"stylesheet\" media=\"screen\" type=\"text/css\" href=\"../css/professor/professor.css\" />");
        out.println("   <link rel=\"stylesheet\" media=\"screen\" type=\"text/css\" href=\"../css/professor/markTheme.css\" />");
        out.println(" </head>");

        out.println(" <body>");

        out.println("   <div id=\"header\">");
        out.println("     <ul>");
        out.println("       <li class=\"menuItem menuItemSpacing\"><a href=\"../Professor\">Accueil</a></li>");
        out.println("       <li class=\"menuItem menuItemSpacing\"><a href=\"ListOfStudents\">Listes des &eacute;tudiants</a></li>");
        out.println("       <li class=\"menuItem menuItemSpacing cursor\">Emploi du temps");
        out.println("         <ul class=\"subMenuBar\">");
        out.println("           <li class=\"subMenu\"><a href=\"ScheduleOfCoursesAndExams\">Cours et examens</a></li>");
        out.println("           <li class=\"subMenu\"><a href=\"ScheduleOfWorksToMake\">Rendu de travaux</a></li>");
        out.println("         </ul>");
        out.println("       </li>");
        out.println("       <li class=\"menuItem menuItemSpacing cursor\">Gestion de mati&egrave;re");
        out.println("         <ul class=\"subMenuBar\">");
        for(Integer year:years)
        {
            out.println("           <li class=\"subMenu\"><a href=\"ManagementOfSubjects?year="+year+"\">"+ year +"-"+ (year+1) +"</a></li>");
        }
        out.println("         </ul>");
        out.println("       </li>");
        out.println("       <li id=\"menuItemMargin\" class=\"menuItem\"><a href=\"../j_spring_security_logout\">Se d&eacute;connecter</a></li>");
        out.println("     </ul>");
        out.println("   </div>");

        getDivContent(out, request, response);

        out.println("   <div id=\"footer\">");
        out.println("     <div id=\"copyright\">&copy; Universit&eacute; Paris-Est Marne-la-Vall&eacute;e</div>");
        out.println("     <div>PMLV v1.0 </div>");
        out.println("   </div>");

        out.println(" </body>");

        out.println("</html>");
        out.close();
    }

    /**
     *  Content of page
     */
    private void getDivContent(PrintWriter out, HttpServletRequest request, HttpServletResponse response)
    {
        out.println("   <div id=\"content\">");
        if(idSubject!=-1)
            out.println("     <div id=\"title\">Notes des &eacute;tudiants pour la mati&egrave;re "+subject.getName()+"</div>");
        else
            out.println("     <div id=\"title\">Notes des &eacute;tudiants pour le travaux \""+theme.getName()+"\"</div>");

        out.println("       <form method=\"post\" action=\"MarkTheme\">");
        out.println("         <table id=\"listOfStudentsBySubjectTable\">");
        out.println("           <tr>");
        out.println("             <th>Num&eacute;ro d'&eacute;tudiant</th>");
        out.println("             <th>Nom</th>");
        out.println("             <th>Pr&eacute;nom</th>");
        out.println("             <th>Moyenne</th>");
        if(idSubject!=-1)
        {
            out.println("             <th>Examen</th>");
            out.println("             <th>Projets</th>");
            out.println("             <th>Tds</th>");
            out.println("             <th>Tps</th>");
        }
        out.println("           </tr>");

        for(int i=0;i<students.size();i++)
        {
            if(i%2 == 0) out.println("           <tr class=\"tableLightBackground\">");
            else out.println("           <tr class=\"tableDarkBackground\">");
            out.println("             <td>"+ students.get(i).getNumber() +"</td>");
            out.println("             <td>"+ students.get(i).getLastname() +"</td>");
            out.println("             <td>"+ students.get(i).getFirstname() +"</td>");
            if(idSubject!=-1)
            {
                if(!notes.containsKey(students.get(i).getuId()))
                {
                    out.println("             <td> <input type=\"text\" size=\"2\" name=\"students"+i+"_mark\"> </td>");
                    out.println("             <td> <input type=\"text\" size=\"2\" name=\"students"+i+"_exam\"> </td>");
                    out.println("             <td> &nbsp </td>");
                    out.println("             <td> &nbsp </td>");
                    out.println("             <td> &nbsp </td>");
                }
                else
                {
                    if(notes.get(students.get(i).getuId()).getNote()!=null) out.println("             <td> <input type=\"text\" size=\"2\" name=\"students"+i+"_mark\" value=\""+ notes.get(students.get(i).getuId()).getNote() +"\"> </td>");
                    else out.println("             <td> <input type=\"text\" size=\"2\" name=\"students"+i+"_mark\"> </td>");
                    if(notes.get(students.get(i).getuId()).getNoteExam()!=null) out.println("             <td> <input type=\"text\" size=\"2\" name=\"students"+i+"_exam\" value=\""+ notes.get(students.get(i).getuId()).getNoteExam() +"\"> </td>");
                    else out.println("             <td> <input type=\"text\" size=\"2\" name=\"students"+i+"_exam\"> </td>");
                    out.println("             <td>"+ (notes.get(students.get(i).getuId()).getNoteProject()==null ? "&nbsp" : notes.get(students.get(i).getuId()).getNoteProject()) +"</td>");
                    out.println("             <td>"+ (notes.get(students.get(i).getuId()).getNoteTD()==null ? "&nbsp" : notes.get(students.get(i).getuId()).getNoteTD()) +"</td>");
                    out.println("             <td>"+ (notes.get(students.get(i).getuId()).getNoteTP()==null ? "&nbsp" : notes.get(students.get(i).getuId()).getNoteTP()) +"</td>");
                }
            }
            else
            {
                if(themes_notes.containsKey(students.get(i).getuId())) out.println("             <td> <input type=\"text\" size=\"2\" name=\"students"+i+"_mark\" value=\""+themes_notes.get(students.get(i).getuId()).getNote()+"\" > </td>");
                else out.println("             <td> <input type=\"text\" size=\"2\" name=\"students"+i+"_mark\"> </td>");
            }
            out.println("           </tr>");
        }
        int i=students.size();
        while(i<MAX_STUDENT_BY_PAGE)
        {
            if(i%2 == 0) out.println("           <tr class=\"tableLightBackground\">");
            else out.println("           <tr class=\"tableDarkBackground\">");
            out.println("             <td> &nbsp </td>");
            out.println("             <td> &nbsp </td>");
            out.println("             <td> &nbsp </td>");
            out.println("             <td> &nbsp </td>");
            if(idSubject!=-1)
            {
                out.println("             <td> &nbsp </td>");
                out.println("             <td> &nbsp </td>");
                out.println("             <td> &nbsp </td>");
                out.println("             <td> &nbsp </td>");
            }
            out.println("           </tr>");
            i++;
        }

        out.println("           <tr> <td> &nbsp </td> </tr>");
        out.println("           <tr>");
        out.println("             <td colspan=\"8\"> <input type=\"submit\" name=\"ok\" value=\"Modifier\"> &nbsp &nbsp <input type=\"submit\" name=\"cancel\" value=\"Annuler\"> </td>");
        out.println("           </tr>");
        out.println("         </table>");

        if(request.getParameter("subject")!=null)
            out.println("           <input type=\"hidden\" name=\"subject\" value=\""+idSubject+"\">");
        else if(request.getParameter("theme")!=null)
            out.println("           <input type=\"hidden\" name=\"theme\" value=\""+idTheme+"\">");
        out.println("       </form>");

        out.println("   </div>");
    }
}

